package com.kdzy.lshy.fluxdemo.controller;

import com.kdzy.lshy.fluxdemo.module.MyEvent;
import com.kdzy.lshy.fluxdemo.repository.MyEventRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 事件模型controller
 * @author cly
 *
 */

@RestController
@RequestMapping("/events")
public class MyEventController {

    @Autowired
    private MyEventRepository myEventRepository;

    /**
     * 接受数据流的 Endpoint
     * @param events 数据是 application/stream+json，与 getEvents方法的区别在于这个方法是consume这个数据流；
     * @return null
     */
    @PostMapping(path = "", consumes = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Mono<Void> loadEvents(@RequestBody Flux<MyEvent> events) {
        // 保存接受到的 Flux
        // then方法表示“忽略数据元素，只返回一个完成信号”。
        return this.myEventRepository.insert(events).then();
    }

    /**
     * 发送数据流的 Endpoint
     * @return
     */
    @GetMapping(path = "", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<MyEvent> getEvents() {

        return this.myEventRepository.findBy();
    }

}
